﻿#coding: utf-8

require 'sinatra/jsonp'

get '/users/:range' do
	res = []
	r = params[:range].split('..').map {|d| Integer(d)}
	User.all(:id => (r[0]..r[1])).each {|u| res << u unless u.nil?}
	if params[:format] == 'js' then
		JSONP res.to_json
	else
		body(res.to_json)
		200
	end
end

get '/user/:id' do
	u = User.get(params[:id])
	if u.nil? then
		404
	else
		res = u.to_json
		if params[:format] == 'js' then
			JSONP res
		else
			body(res)
			200
		end
	end
end

get '/user/l/:login' do
	u = User.first(:login => params[:login])
	if u.nil? then
		404
	else
		res = u.to_json
		if params[:format] == 'js' then
			JSONP res
		else
			body(res)
			200
		end
	end
end

put '/user' do
	puts request.body.string
	begin
		data = JSON.parse(request.body.string)
	rescue JSON::ParserError
		400
	end
	if data.nil? or !data.has_key?('login') or !data.has_key?('password') or !data.has_key?('mail') or !data.has_key?('lastName') or !data.has_key?('firstName') then
		400
	else
		u = User.create(
			:login => data['login'],
			:password => data['password'],
			:mail => data['mail'],
			:lastname => data['lastName'],
			:firstname => data['firstName'],
			:isAdmin => data['isAdmin'],
			:created_at => Time.now,
			:updated_at => Time.now
		)
		u.save
		body(u.id.to_s)
		200
	end
end

delete '/user/:id' do
	user = User.get(params[:id])
	if user.nil? then
		404
	elsif user.destroy then
		200
	else
		400
	end
end

post 'user/:id' do
	begin
		data = JSON.parse(request.body.string)
	rescue JSON::ParserError
		400
	end
	if data.nil? then
		400
	else
		user = User.get(params[:id])
		if user.nil?
			400
		else
			if user.login != data['login'] then 
				user.update(:login => data['login'])
			end
			if user.password != data['password'] then
				user.update(:password => data['password'])
			end
			if user.mail != data['mail'] then
				user.update(:mail => data['mail'])
			end
			if user.lastname != data['lastname'] then
				user.update(:lastname => data['lastname'])
			end
			if user.firstname != data['firstname'] then
				user.update(:firstname => data['firstname'])
			end
			200
		end
	end
end
